package com.mobi.Survey;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.appbucks.sdk.AppBucksBanner;
import com.mobi.Survey.Exceptions.EmptyFieldException;
import com.mobi.Survey.controller.Singleton;
import com.mobi.Survey.controller.SurveyDetailPojo;
import com.mobi.Survey.controller.SurveyPojo;
import com.mobi.Survey.controller.SurveyResultPojo;
import com.mobi.Survey.controller.User;
import com.mobi.Survey.controller.WebServiceIO;
import com.mobi.Survey.model.AbstractTable;
import com.mobi.Survey.model.SurveyDetailTable;
import com.mobi.Survey.model.SurveyTable;
import com.mobi.Survey.uicomponents.ControlFactory;
import com.mobi.Survey.utils.Helper;
import com.mobi.Survey.video.VideoPlayer;
import com.mobi.Survey.video.YouTubeUtility;

/**
 * 
 * <p>
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * SurveyDetailScreen.java This class is responsible for displaying survey
 * detail. user passes survey id for this class
 */
public class SurveyDetailScreen extends AbstractScreen
{
	private List<String> videoUrls = new ArrayList<String>();
	private List<Bitmap> bitmapsVids = new ArrayList<Bitmap>();
	private List<Object> viewVids = new ArrayList<Object>();
	private View parent;
	private ImageView ivBgImage;
	/**
	 * if single screen button will be added other wise image view will be added
	 */
	private List<Object> ivsProduct = new ArrayList<Object>();
	private List<String> imageUrls = new ArrayList<String>();
	private List<Bitmap> bitmapsProduc = new ArrayList<Bitmap>();

	private boolean singleScreen;

	private SurveyPojo survey;

	private AppBucksBanner banner;
	private TextView txtPageNumber;
	private Button btnPrevious;
	private Button btnNext;
	private Button btnSubmit;
	// private Bitmap background;
	private List<View> views = new ArrayList<View>();
	private List<SurveyDetailPojo> sdps;

	private int currentCompIndex = 0;
	private int lastComponent = 0;
	private long surveyId;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// hideTitle = true;
		super.onCreate(savedInstanceState);

		Intent intent = getIntent();

		if (intent != null)
		{
			Bundle bundle = intent.getExtras();
			if (bundle != null)
			{
				surveyId = ((Long) bundle.get("data")).intValue();
				SurveyTable sdTable = new SurveyTable(this);
				survey = sdTable.getSurveys(true, false, this, surveyId).get(0);
				sdTable.closeDB();
			}

		}
		setTitle(survey.getSurveyDiscription());

		String txtColor = survey.getFontColor();
		// If we have color data available use it
		if (null != txtColor && txtColor.length() > 0)
			txtPageNumber.setTextColor(Color.parseColor("#" + txtColor));

		// txtSurveyTitle.setText();
		new LongTask().execute(surveyId);

		// Set Header View background
		showHeaderImage(User.getInstance().getDetailImage());

	}

	@Override
	protected void onStart()
	{

		super.onStart();
		if (User.getInstance().isShowAds()
				&& Helper.isNetworkAvailable(getBaseContext()) && ADS_ENABLE)
		{
			if (banner.getVisibility() == View.GONE)
				banner.setVisibility(View.VISIBLE);
			banner.showAd();
		}
	}

	@Override
	public void onBackPressed()
	{
		// TODO Auto-generated method stub
		super.onBackPressed();
		// AppBucksAPI.showInterstitial(this);
	}

	/**
	 * creates controls dynamically on the base of survey detail data if survey
	 * type is single screen all controls are displayed other wise other
	 * controls are made invisible
	 */
	private void createViews()
	{
		singleScreen = survey.isSinglePage();

		ViewGroup vg = (ViewGroup) findViewById(R.id.llSurveyDetailSingle);

		if (vg != null && sdps != null && sdps.size() > 0)
		{

			// boolean firstImage = true;
			for (SurveyDetailPojo sdp : sdps)
			{

				View v = ControlFactory.createControl(sdp, this, singleScreen);
				if (v == null)
				{
					printLogMessage("Invalid Control Found with Control No: "
							+ sdp.getControlType());
					continue;
				}

				// If not single screen we are making control invisible
				if (!singleScreen)
				{
					v.setVisibility(View.GONE);

				}
				// if control type is Video View perform necessary action on
				// video control
				if (sdp.getControlType() == ControlFactory.CONTROL_VIDEO_VIEW)
				{

					performActionOnVideoControl(sdp, v);

				}
				// if control type is Image View perform necessary action on
				// Image control
				// if it is frist product image we will not not make it
				// part of control we will just download it and display
				// as background
				if (sdp.getControlType() == ControlFactory.CONTROL_IMAGE_VIEW)
				{
					// if (firstImage) {
					// firstImage = false;
					//
					// performActionOnImageControl(sdp);
					// continue;
					// }
					performActionOnImageControl(sdp, v);

				}

				vg.addView(v);
				views.add(v);

			}

			new DownloadImageFile().execute();

			lastComponent = views.size() - 1;
			if (!singleScreen)
			{
				// because it is single component per screen we are making first
				// item visible
				views.get(0).setVisibility(View.VISIBLE);
				btnSubmit.setVisibility(View.GONE);
				refreshButtonsState();
				// setting current page number of total page
				StringBuilder sbTxtPageNumber = new StringBuilder();
				sbTxtPageNumber.append("(");
				sbTxtPageNumber.append(currentCompIndex + 1);
				sbTxtPageNumber.append(" of ");
				sbTxtPageNumber.append(lastComponent + 1);
				sbTxtPageNumber.append(")");
				txtPageNumber.setText(sbTxtPageNumber.toString());

			} else
			{
				btnNext.setVisibility(View.GONE);
				btnPrevious.setVisibility(View.GONE);
				txtPageNumber.setVisibility(View.GONE);
			}

		}

		else
		{
			// printMessage("View Group Null Include header");
			showShortToast(Messages.NO_SURVEY_DETAIL);
		}
	}

	private void showDuplicateAnswerDialogue(String message)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(message)
				.setCancelable(false)
				.setPositiveButton(Messages.RESUBMIT_ANSWER,
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog, int id)
							{

								new ResultSubmitTask().execute();

							}
						})
				.setNegativeButton(Messages.CANCEL,
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog, int id)
							{

							}
						});

		AlertDialog alert = builder.create();
		alert.show();
	}

	@Override
	protected void initUiVars()
	{
		btnNext = (Button) findViewById(R.id.btnNext);
		btnPrevious = (Button) findViewById(R.id.btnPrevious);
		btnSubmit = (Button) findViewById(R.id.btnSubmit);
		parent = findViewById(R.id.parent);
		ivBgImage = (ImageView) findViewById(R.id.ivBgImage);
		// Added to support ads banner
		banner = (AppBucksBanner) findViewById(R.id.banner);

		// Image header added now user logins WS will return Banner image and
		// its size
		headerImage = findViewById(R.id.headerImage);

		if (!singleScreen)
		{
			txtPageNumber = (TextView) findViewById(R.id.txtPageNumber);

		}
	}

	@Override
	protected int getLayoutId()
	{
		return LayoutIds.SURVEY_DETAIL_SCREEN;
	}

	@Override
	protected void onRelease()
	{
		survey.getSurveyDetail().clear();

		for (Bitmap b : bitmapsVids)
		{
			if (b != null && !b.isRecycled())
			{
				b.recycle();
				b = null;
			}
		}

		if (survey.getBgImageBitmap() != null
				&& !survey.getBgImageBitmap().isRecycled())
		{
			survey.getBgImageBitmap().recycle();
			survey.setBgImageBitmap(null);
		}
		bitmapsVids.clear();
		bitmapsVids = null;
		for (Bitmap b : bitmapsProduc)
		{
			if (b != null)
			{
				b.recycle();
			}
		}
		bitmapsProduc.clear();
		bitmapsProduc = null;
		if (sdps != null)
		{
			sdps.clear();
		}
		views.clear();

		if (Singleton.getInstance().getBitmapProduct() != null
				&& !Singleton.getInstance().getBitmapProduct().isRecycled())
		{
			Singleton.getInstance().getBitmapProduct().recycle();
			Singleton.getInstance().setBitmapProduct(null);
		}

		ivBgImage.setBackgroundDrawable(null);
		survey = null;

	}

	private boolean clickable = true;

	public void btnClick(View v)
	{

		int id = v.getId();

		if (id == R.id.btnSubmit)
		{

			// If user have no data related to submit survey we simply submit it
			// else we ask user to confirm that if user want to resubmit in case
			// if user resubmit old survey result data will be deleted
			if (SurveyResultPojo.isNew(surveyId, SurveyDetailScreen.this) == 0)
			{
				new ResultSubmitTask().execute();
			} else
			{
				showDuplicateAnswerDialogue(Messages.ALREADY_ANSWERED);
			}

		} else if (id == R.id.btnNext && clickable)
		{
			clickable = false;
			onBtnNext();
			clickable = true;

		} else if (id == R.id.btnPrevious && clickable)
		{
			clickable = false;
			onBtnPrevious();
			clickable = true;
		}

	}

	private void onBtnPrevious()
	{

		if (!singleScreen)
		{
			StringBuilder sbTxtPageNumber = new StringBuilder();
			currentCompIndex--;
			sbTxtPageNumber.append("(");
			sbTxtPageNumber.append(currentCompIndex + 1);
			sbTxtPageNumber.append(" of ");
			sbTxtPageNumber.append(lastComponent + 1);
			sbTxtPageNumber.append(")");
			txtPageNumber.setText(sbTxtPageNumber.toString());

		}
		byte reverse = 0;
		refreshControlsVisibility(reverse);

	}

	private void onBtnNext()
	{

		if (!singleScreen)
		{
			StringBuilder sbTxtPageNumber = new StringBuilder();
			currentCompIndex++;

			sbTxtPageNumber.append("(");
			sbTxtPageNumber.append(currentCompIndex + 1);
			sbTxtPageNumber.append(" of ");
			sbTxtPageNumber.append(lastComponent + 1);
			sbTxtPageNumber.append(")");

			txtPageNumber.setText(sbTxtPageNumber.toString());

		}
		byte forward = 1;
		refreshControlsVisibility(forward);

	}

	private void refreshControlsVisibility(byte direction)
	{

		if (direction == 1)
		{
			views.get(currentCompIndex).setVisibility(View.VISIBLE);
			if (currentCompIndex >= 0)
			{
				views.get(currentCompIndex - 1).setVisibility(View.GONE);

			}
		} else
		{
			views.get(currentCompIndex).setVisibility(View.VISIBLE);
			if (currentCompIndex >= 0)
			{
				views.get(currentCompIndex + 1).setVisibility(View.GONE);
			}
		}

		refreshButtonsState();
	}

	private void refreshButtonsState()
	{
		if (currentCompIndex == 0)
		{
			btnPrevious.setEnabled(false);
		}
		if (currentCompIndex == lastComponent)
		{
			btnNext.setEnabled(false);
			btnSubmit.setVisibility(View.VISIBLE);
		}
		if (currentCompIndex > 0)
		{
			btnPrevious.setEnabled(true);
		}
		if (currentCompIndex < lastComponent)
		{
			btnNext.setEnabled(true);
		}

	}

	/**
	 * 
	 * @param surveyDetailPojo
	 * @param view
	 *            <p>
	 *            If Survey Detail type was single screen we created Button for
	 *            Video and Image control so on user click we display image and
	 *            video in separate screen we also keep reference of our buttons
	 *            or image preview in a Collection to track user click
	 * 
	 */
	private void performActionOnVideoControl(
			final SurveyDetailPojo surveyDetailPojo, View view)
	{
		String vid = surveyDetailPojo.getControlParameter();
		videoUrls.add(vid);
		ImageView iv = null;
		// If not single screen we have image views for preview of video control
		if (!singleScreen)
		{
			int index = 0;
			if (surveyDetailPojo.getControlText() != null
					&& surveyDetailPojo.getControlText().length() > 0)
			{
				{
					index++;
				}

			}
			iv = (ImageView) ((ViewGroup) view).getChildAt(index);
			viewVids.add(iv);
			iv.setOnClickListener(new View.OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					int indexOf = viewVids.indexOf(v);
					String vidUrl = videoUrls.get(indexOf);
					byte videoType = 0;
					if (vidUrl.contains("youtube"))
					{
						videoType = VideoPlayer.TYPE_YOUTUBE;
					} else
					{
						videoType = VideoPlayer.TYPE_GENERIC;
					}
					// if (videoType == VideoPlayer.TYPE_YOUTUBE) {

					switchScreenTo(VideoScreen.class, videoType + vidUrl);
					// } else {
					// switchScreenTo(VideoScreen.class, videoType + vidUrl);

					// }

				}
			});

		} else
		{
			// If Single screen we have button for video control to let the user
			// open Video Screen
			int index = 0;
			if (surveyDetailPojo.getControlText() != null
					&& surveyDetailPojo.getControlText().length() > 0)
			{
				{
					index++;
				}

			}
			Button btn = (Button) ((ViewGroup) view).getChildAt(index);

			viewVids.add(btn);
			btn.setOnClickListener(new View.OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					int indexOf = viewVids.indexOf(v);
					String vidUrl = videoUrls.get(indexOf);
					byte videoType = 0;
					if (vidUrl.contains("youtube"))
					{
						videoType = VideoPlayer.TYPE_YOUTUBE;
					} else
					{
						videoType = VideoPlayer.TYPE_GENERIC;
					}

					// if (videoType == VideoPlayer.TYPE_YOUTUBE) {

					// switchScreenTo(VideoScreen.class, videoType + vidUrl);
					// } else {
					switchScreenTo(VideoScreen.class, videoType + vidUrl);

					// }

				}
			});
		}
		// If video type is not youtube we don't have preview image so display
		// preview image from resource

		if (!vid.contains("youtube") && !singleScreen && iv != null)
			iv.setImageResource(R.drawable.nopreview);

	}

	/**
	 * 
	 * @param surveyDetailPojo
	 *            <p>
	 *            add product image url on collection so later we will download
	 *            these images to display in background task
	 */
	// private void performActionOnImageControl(SurveyDetailPojo
	// surveyDetailPojo) {
	//
	// String imgUrl = surveyDetailPojo.getControlParameter();
	// imageUrls.add(imgUrl);
	//
	// }

	/**
	 * If single screen we will display button for image control other wise we
	 * will display image
	 * 
	 * @param surveyDetailPojo
	 * @param view
	 */
	private void performActionOnImageControl(SurveyDetailPojo surveyDetailPojo,
			View view)
	{

		String imgUrl = surveyDetailPojo.getControlParameter();
		imageUrls.add(imgUrl);

		if (!singleScreen)
		{
			int index = 0;
			if (surveyDetailPojo.getControlText() != null
					&& surveyDetailPojo.getControlText().length() > 0)
			{
				{
					index++;
				}

				// imgProduct.setImageResource(R.drawable.tempproduct);

			}
			View v = ((ViewGroup) view).getChildAt(index);
			ivsProduct.add(v);
		} else
		{

			int index = 0;
			if (surveyDetailPojo.getControlText() != null
					&& surveyDetailPojo.getControlText().length() > 0)
			{
				{
					index++;
				}

			}
			Button btn = (Button) ((ViewGroup) view).getChildAt(index);

			ivsProduct.add(btn);
			btn.setOnClickListener(new View.OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					int indexOf = ivsProduct.indexOf(v);

					Singleton.getInstance().setBitmapProduct(
							bitmapsProduc.get(indexOf));
					switchScreenTo(ImageViewScreen.class);

				}
			});

		}

	}

	private class DownloadImageFile extends AsyncTask<String, Integer, String>
	{

		private ProgressDialog mProgressDialog;

		private String msg;
		ArrayList<String> localPathImg = new ArrayList<String>();
		ArrayList<String> localPathVideo = new ArrayList<String>();

		protected void onPreExecute()
		{

			super.onPreExecute();

			mProgressDialog = new ProgressDialog(SurveyDetailScreen.this);
			mProgressDialog.setMessage(Messages.DOWNLOAD_PRODUCT_IMGS);
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setCancelable(false);

			mProgressDialog.show();
		}

		protected String doInBackground(String... url)
		{

			try
			{

				String imageUrl = survey.getbGImageUrl();
				if (null != imageUrl && imageUrl.length() > 0)
				{

					String outputfile = Helper.getTempFile(Helper
							.getHashNameFromUrl(imageUrl) + "");
					if (!new File(outputfile).exists())
						Helper.downloadFile(imageUrl, outputfile);

					survey.setBgImageBitmap(BitmapFactory
							.decodeFile(outputfile));
				}
			} catch (Exception e)
			{

			}
			int size = imageUrls.size();
			// for each image url and video(Preview image of video) we will
			// download that image and save it in
			// application specific directory
			// with name of Hash code which we calculate from url
			// if a file with same hash code already exist we don't download
			for (int i = 0; i < size; i++)
			{
				String imgUrl = imageUrls.get(i);

				int imgHashName = Helper.getHashNameFromUrl(imgUrl);
				Bitmap b = null;
				String local = Helper.getTempFile(imgHashName + "");
				localPathImg.add(local);
				if (Helper.isFileExist(local))
				{
					b = Helper.decode(local, 3);

				} else
				{
					try
					{
						Helper.downloadFile(imgUrl, local);
						b = Helper.decode(local, 3);

					} catch (IOException e)
					{
						msg = Messages.IMG_NOT_FOUND;
						printMessage("Helper.downloadFile(imgProductUrl, productImgPath)");

					}

				}
				// if (i == 0) {
				// background = b;
				// b = null;
				// continue;
				// } else
				bitmapsProduc.add(b);

			}
			// If video type is youtube we get preview image from youtube using
			// http://i.ytimg.com/vi/" + Youtube Video Id + "/0.jpg
			// If video type is any other we don't have preview image so we just
			// display no preview image from resource
			if (!singleScreen)
			{

				int siz = videoUrls.size();
				publishProgress(50);
				for (int i = 0; i < siz; i++)
				{

					String video = videoUrls.get(i);
					byte videoType = 0;
					if (video.contains("youtube"))
					{
						videoType = VideoPlayer.TYPE_YOUTUBE;
					} else
					{
						videoType = VideoPlayer.TYPE_GENERIC;
					}
					if (videoType == VideoPlayer.TYPE_YOUTUBE)
					{

						Bitmap b = null;
						String yId = YouTubeUtility.getVideoIdFromUrl(video);
						String vImg = "http://i.ytimg.com/vi/" + yId + "/0.jpg";
						int hash = Helper.getHashNameFromUrl(vImg);
						String videoPreviewImgPath = Helper.getTempFile(hash
								+ "");
						localPathVideo.add(videoPreviewImgPath);
						if (Helper.isFileExist(videoPreviewImgPath))
						{
							b = Helper.decode(videoPreviewImgPath, 1);
							bitmapsVids.add(b);
						} else
						{
							try
							{

								Helper.downloadFile(vImg, videoPreviewImgPath);
								b = Helper.decode(videoPreviewImgPath, 1);
								bitmapsVids.add(b);
							} catch (IOException e)
							{
								printMessage("Helper.downloadFile(imgProductUrl, productImgPath)");
								msg = Messages.NO_PREVIEW_IMAGE;
							}

						}
					} else
					{
						bitmapsVids.add(null);
					}

				}
			}
			return null;
		}

		protected void onPostExecute(String result)
		{

			super.onPostExecute(result);

			if (survey.getBgImageBitmap() != null
					&& !survey.getBgImageBitmap().isRecycled())
			{

				ivBgImage.setBackgroundDrawable(new BitmapDrawable(survey
						.getBgImageBitmap()));

			} else
			{
				ivBgImage.setVisibility(View.GONE);
			}
			String bgColor = survey.getbGColor();
			if (null != bgColor && bgColor.length() > 0)
			{
				parent.setBackgroundColor(Color.parseColor("#" + bgColor));
			}
			int size = ivsProduct.size();

			if (!singleScreen)
			{
				for (int i = 0; i < size; i++)
				{
					ImageView ivProduct = (ImageView) ivsProduct.get(i);
					Bitmap product = bitmapsProduc.get(i);
					// if (i == 0)
					if (ivProduct != null)
					{
						if (product != null)
						{
							ivProduct.setImageBitmap(product);
						} else
						{
							ivProduct.setImageResource(R.drawable.nopreview);
						}
					}
				}

				size = viewVids.size();
				for (int i = 0; i < size; i++)
				{
					ImageView ivVideo = null;
					String video = videoUrls.get(i);
					byte videoType = 0;
					if (video.contains("youtube"))
					{
						videoType = VideoPlayer.TYPE_YOUTUBE;
					} else
					{
						videoType = VideoPlayer.TYPE_GENERIC;
					}

					if (viewVids.get(i) instanceof ImageView)
					{
						ivVideo = (ImageView) viewVids.get(i);
					}
					if (ivVideo == null)
						continue;
					if (videoType == VideoPlayer.TYPE_YOUTUBE)
					{
						Bitmap bitmapVideo = bitmapsVids.get(i);
						if (bitmapVideo != null)
						{
							ivVideo.setImageBitmap(bitmapVideo);
						} else
						{
							ivVideo.setImageResource(R.drawable.nopreview);
						}
					} else
					{

						ivVideo.setImageResource(R.drawable.nopreview);
					}

				}

			}

			mProgressDialog.dismiss();
			mProgressDialog = null;
			if (msg != null)
			{
				showAlert(msg);
			}

		}

		protected void onProgressUpdate(Integer... values)
		{

			super.onProgressUpdate(values);

			if (values[0] == 50)
				mProgressDialog
						.setMessage(Messages.DOWNLOADING_VIDEO_PREVIEW_IMG);
			;
		}

	}

	/**
	 * 
	 * @author Yahya Arshad Retrieve Image Survey detail data in background
	 *         after Retrieving create views on base of that data
	 */
	private class LongTask extends AsyncTask<Long, Integer, Object>
	{
		ProgressDialog progressDialog = null;

		protected Object doInBackground(Long... params)
		{
			long surveyId = params[0];
			AbstractTable at = new SurveyDetailTable(SurveyDetailScreen.this);
			sdps = ((SurveyDetailTable) at).getSurveyDetail(surveyId);
			for (SurveyDetailPojo sdp : sdps)
			{
				sdp.setSurvey(survey);

			}
			at.closeDB();
			SurveyResultPojo.writeSurveyResult(surveyId, sdps,
					SurveyDetailScreen.this);

			return null;

		}

		protected void onPostExecute(Object result)
		{

			super.onPostExecute(result);
			createViews();
			progressDialog.dismiss();
			progressDialog = null;

		}

		protected void onPreExecute()
		{

			super.onPreExecute();
			try
			{
				progressDialog = ProgressDialog.show(SurveyDetailScreen.this,
						"", Messages.FETCHING_SURVEY_DETAIL);
			} catch (Exception e)
			{
				e.printStackTrace();
			}

		}

	}

	/**
	 * 
	 * Submit user result to server on ok response submitted survey data will be
	 * entered to users database too.
	 */
	private class ResultSubmitTask extends AsyncTask<Long, Integer, Boolean>
	{
		ProgressDialog progressDialog = null;
		private String message;

		protected Boolean doInBackground(Long... params)
		{
			try
			{
				ControlFactory.getUserInputs(sdps, views);
				// If we are in debug mode we will not submit survey to server
				// so we simply return true to let survey commit in local db

				return WebServiceIO.submitResult(sdps, surveyId);

			} catch (EmptyFieldException e)
			{
				message = e.getMessage();
				// e.printStackTrace();
				return false;
			} catch (Exception e)
			{
				message = Messages.SURVEY_CAN_NOT_SUBMIT;
				return false;
			}

		}

		protected void onPostExecute(Boolean response)
		{

			super.onPostExecute(response);
			progressDialog.dismiss();
			progressDialog = null;
			if (response)
			{
				// delete if any survey result data already exist
				SurveyResultPojo.delete(surveyId, SurveyDetailScreen.this);
				SurveyResultPojo
						.commit(surveyId, sdps, SurveyDetailScreen.this);
				showLongToast(Messages.SURVEY_SUBMITTED);
				finish();

			} else
			{
				// In case of false response from server
				showAlert(message);
			}

		}

		protected void onPreExecute()
		{

			super.onPreExecute();
			try
			{
				progressDialog = ProgressDialog.show(SurveyDetailScreen.this,
						"", Messages.SUBMITTING_SURVEY);
			} catch (Exception e)
			{
				e.printStackTrace();
			}

		}

	}

}
